package com.bdqn.dao;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class BaseDao {
private static final Logger log= LogManager.getLogger(BaseDao.class);
private static final String configPath="database.properties";
private static String driver=null;
private static String url=null;
private static String username=null;
private static String password=null;
static {
    loadProperties();
    loadDriver();
}
private static void loadProperties(){
    Properties prop=new Properties();
    try {
        prop.load(BaseDao.class.getClassLoader().getResourceAsStream(configPath));
        driver=prop.getProperty("driver");
        url=prop.getProperty("url");
        username=prop.getProperty("username");
        password= prop.getProperty("password");
    } catch (IOException e) {
        log.error(e.fillInStackTrace());
    }
}
private static void loadDriver(){
    try {
        Class.forName(driver);

    } catch (ClassNotFoundException e) {

        log.error(e.fillInStackTrace());

    }

}

public static Connection getConnection(){

    Connection conn=null;

    try {

        conn= DriverManager.getConnection(url,username,password);

    } catch (SQLException e) {

        log.error(e.fillInStackTrace());

    }

    return conn;

}

public static void CloAll(ResultSet rs, Statement pstmt ,Connection conn){

    if(rs!=null){

        try {

            rs.close();

        } catch (SQLException e) {

            log.error(e.fillInStackTrace());

        }

    }

    if(pstmt!=null){

        try {

            pstmt.close();

        } catch (SQLException e) {

            log.error(e.fillInStackTrace());

        }

    }

    if(conn!=null){

        try {

            conn.close();

        } catch (SQLException e) {

            log.error(e.fillInStackTrace());

        }

    }

}

public static int executeUpdate(String sql,Object[]param){

    int row=1;

    Connection conn=getConnection();

    PreparedStatement pstmt=null;

    try {

        pstmt=conn.prepareStatement(sql);

        for (int i = 0; i < param.length; i++) {

            pstmt.setObject(i+1,param[i]);

        }

        row= pstmt.executeUpdate();

    } catch (SQLException e) {

        log.error(e.fillInStackTrace());

    }finally {

        CloAll(null,pstmt,conn);

    }

    return row;

    }

}
